package com.yumeko;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import uitl.JSONSerializer;
import uitl.RpcDecoder;
import uitl.RpcEncoder;
import uitl.RpcRequest;

import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @program: netty-dubbo-zhenghao
 * @description:
 * @author: Zheng Hao
 * @create: 2020-03-12 14:45
 */
public class RpcConsumer {
    private static UserClientHandler userClientHandler;
    //创建线程池对象
    private static ExecutorService executor = Executors.newFixedThreadPool((int) (Runtime.getRuntime().availableProcessors() / (1 - 0.8)));

    //1.创建一个代理对象 providerName：UserService#sayHello are you ok?
    public Object createProxy(final Class<?> serviceClass, final String providerName) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(), new Class<?>[]{serviceClass}, (proxy, method, args) -> {
            //调用初始化netty客户端的方法
            if (userClientHandler == null) {
                initClient();
            }
            String classname = method.getDeclaringClass().getName();
            String name = method.getName();
            Class<?>[] parameterTypes = method.getParameterTypes();
            RpcRequest rpcRequest = new RpcRequest(providerName + args[0], classname, name, parameterTypes, args, null);
            userClientHandler.setRpcRequest(rpcRequest);
            // 设置要发给服务器端的信息
            //userClientHandler.setPara(providerName + args[0]);
            Object o = executor.submit(userClientHandler).get();
            return o;
        });
    }

    //2.初始化netty客户端
    public static void initClient() throws InterruptedException {
        userClientHandler = new UserClientHandler();

        EventLoopGroup group = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new RpcEncoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(userClientHandler);
                    }
                });

        bootstrap.connect("127.0.0.1", 6666).sync();
    }
}
